<?php
/**
 * The Dispatcher class
 *
 * @todo avoid code redundance of dispatchAction() and dispatchComponent()
 */
class Dispatcher
{
	/**
	 * Constructor placeholder
	 * Prevent the Dispatcher class from instantiating
	 * Singleton Pattern
	 */
	private function __construct()
	{
	}

	/**
	 * Disptach the module/action calling.
	 *
	 * @param $module string
	 * @param $action string
	 * @return void
	 * @todo allow one action dispatch another action
	 */
	static public function dispatchAction($module, $action)
	{
		$actionFile = Kiwi::$applicationDir . 'module' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'action' . DIRECTORY_SEPARATOR . $action . 'Action.php';
		if (file_exists($actionFile))
		{
			include($actionFile);
		}
		else
		{
			if (function_exists('onActionNotFound'))
			{
				call_user_func('onActionNotFound', $module, $action);
			}
			else
			{
				throw new Exception("Action not found: $module/$action");
			}
		}
		$actionClassName = $action . 'Action';
		if (!class_exists($actionClassName, false))
		{
			DebugHelper::debug('ACTION_CLASS_NOT_FOUND', array('action' => $action));
		}
		else
		{
			$actionInstance = new $actionClassName;
			$actionInstance->afterConstruct();
			$actionInstance->uri['module'] = $module;
			$actionInstance->uri['action'] = $action;
			$actionInstance->view->uri = $actionInstance->uri;
			$actionInstance->view->setTemplate($action);
			$actionInstance->view->setLayoutDir(Kiwi::$applicationDir . 'layout' . DIRECTORY_SEPARATOR);
			$actionInstance->view->setTemplateDir(Kiwi::$applicationDir . 'module' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR);
			call_user_func(array($actionInstance, 'execute'));
		}
	}

	/**
	 * Disptach the module/component calling.
	 *
	 * @param $module string
	 * @param $component string
	 * @param $data mixed
	 * @return void
	 */
	static public function dispatchComponent($module, $component, $data = null)
	{
		$componentClassName = $component . 'Component';
		if (!class_exists($componentClassName, false))
		{
			DebugHelper::debug('COMPONENT_CLASS_NOT_FOUND', array('component' => $component));
		}
		else
		{
			$componentInstance = new $componentClassName;
			$componentInstance->afterConstruct();
			$componentInstance->view->setTemplate($component);
			$componentInstance->view->setLayoutDir(Kiwi::$applicationDir . 'layout' . DIRECTORY_SEPARATOR);
			$componentInstance->view->setTemplateDir(Kiwi::$applicationDir . 'module' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR);
			call_user_func(array($componentInstance, 'execute'), $data);
		}
	}
}
